package com.ellecity06.cwhiskymall.base

import androidx.lifecycle.viewModelScope
import com.ellecity06.common.base.BaseMviViewModel
import com.ellecity06.common.base.view.IUiIntent
import com.ellecity06.common.base.view.IUiState
import com.ellecity06.common.http.entity.ApiResponse
import com.ellecity06.common.ktx.SharedFlowEvents
import com.ellecity06.common.ktx.postEvent
import com.ellecity06.cwhiskymall.base.vm.PageIntent
import com.ellecity06.cwhiskymall.base.vm.PageState
import com.ellecity06.cwhiskymall.bean.response.BaseListResponse
import com.ellecity06.cwhiskymall.http.ApiService
import com.ellecity06.cwhiskymall.http.request
import kotlinx.coroutines.channels.Channel
import kotlinx.coroutines.flow.asSharedFlow
import kotlinx.coroutines.flow.consumeAsFlow
import kotlinx.coroutines.launch

/**
 * @author ellecity06
 * @time 2024/10/24 15:26
 * @des
 */
abstract class BasePageViewModel<T : IUiState, D : IUiIntent> : BaseMviViewModel<T, D>() {

    //创建意图管道，容量无限大
    val pageIntent = Channel<PageIntent>(Channel.UNLIMITED)

    protected val mPageState = SharedFlowEvents<PageState>()
    val pageState = mPageState.asSharedFlow()

    init {
        viewModelScope.launch {
            //收集意图
            pageIntent.consumeAsFlow().collect {
                when (it) {
                    PageIntent.Refresh -> {
                        pagerHelper.pageIndex = 1
                        fetchData()
                    }

                    PageIntent.LoadMore -> {
                        fetchData()
                    }
                }

            }
        }

    }

    abstract fun fetchData()

    protected suspend fun <T> onFetchPageSuccess(it: List<T>?) {
        if (it != null) {
            if (it.isNotEmpty()) {
                val hasMore = it.size >= pagerHelper.pageSize
                if (pagerHelper.pageIndex == 1) {
                    mPageState.postEvent(PageState.RefreshSuccess(it, hasMore))
                } else {
                    mPageState.postEvent(PageState.LoadMoreSuccess(it, hasMore))
                }
                pagerHelper.pageIndex++
            } else {
                if (pagerHelper.pageIndex == 1) {
                    mPageState.postEvent(PageState.RefreshSuccess(emptyList<T>(), false))
                } else {
                    mPageState.postEvent(PageState.NoMore)
                }
            }
        }
    }

    protected fun onFetchPageError(msg: String?) {
        if (pagerHelper.pageIndex == 1) {
            viewModelScope.launch { mPageState.postEvent(PageState.RefreshError(msg?:"未知错误")) }
        } else {
            viewModelScope.launch { mPageState.postEvent(PageState.LoadError) }
        }

    }

    /**
     *
     */
    protected fun <T> requestPageList(api: suspend ApiService.() -> ApiResponse<BaseListResponse<T>>) {
        request(success = {
            onFetchPageSuccess(it?.records)
        }, api = api, error = {
            onFetchPageError(it.message)
        })
    }

    protected fun <T> requestList(api: suspend ApiService.() -> ApiResponse<List<T>>) {
        request(success = {
            onFetchPageSuccess(it)
        }, api = api, error = { onFetchPageError(it.message) })
    }
}